package com.smartentities.json.generator.generators;

import org.everit.json.schema.ArraySchema;
import org.everit.json.schema.ObjectSchema;
import org.everit.json.schema.Schema;
import org.json.JSONArray;

import com.smartentities.json.generator.GeneratorFactory;

public class ArrayGenerator extends JsonValueGenerator<JSONArray> {

	public ArrayGenerator(Schema schema) {
		super(schema);
	}

	@Override
	public JSONArray generate() {

		if (schema instanceof ArraySchema) {
			ArraySchema arraySchema = (ArraySchema) schema;

			Schema allItemSchema = arraySchema.getAllItemSchema();

			JSONArray jsonArray = new JSONArray();

			// 当 array 为 [] 时会报 null 指针异常。所以这里做一下判断，只有 ObjectSchema 才会生成数据，否则直接返回 []
			if (allItemSchema instanceof ObjectSchema) {
				jsonArray.put(GeneratorFactory.getGenerator(allItemSchema).generate());
			}

			return jsonArray;
		}
		return new JSONArray();
	}
}